
#import "GLKitViewController.h"
#import <OpenGLES/ES1/gl.h>

@implementation GLKitViewController

#pragma mark - Initialization

- (id) initWithNibName: (NSString *) nibNameOrNil bundle: (NSBundle *) nibBundleOrNil
{
    self = [super initWithNibName: nibNameOrNil bundle: nibBundleOrNil];
    if (self) {
        GLKView *view = (GLKView *) self.view;
        eaglContext = [EAGLContext alloc];
        view.context = [eaglContext initWithAPI: kEAGLRenderingAPIOpenGLES1];
        self.preferredFramesPerSecond = 33;        
    }
    return self;
}

#pragma mark - GLKView and GLKViewController delegate methods

- (void) update
{
    //update game logic
}

- (void) glkView: (GLKView *) view drawInRect: (CGRect) rect
{
    static float b = 0;
    b += 0.001;
    
    //render game
    glClearColor(0.1, 0.5, 0.1 + b, 1.0); 
    glClear(GL_COLOR_BUFFER_BIT);   
        
    [self setOGLProjection];
    [self drawOGLTriangle];    
}

#pragma mark - OpenGL

- (void) setOGLProjection {    
    glLoadIdentity(); 
    int w = self.view.bounds.size.width;
    int h = self.view.bounds.size.height; 
    
    //The old way
    //glOrthof(0, w, h, 0, 0, 1); //2D-Perspektive
    
    //GLKit
    GLKMatrix4 m4 = GLKMatrix4MakeOrtho(0, w, h, 0, 0, 1); 
    glMultMatrixf(m4.m);
} 

- (void) drawOGLTriangle {    
    static int x = 0; x++;
    GLshort vertices[ ] = {
        x + 0,   250, 
        x + 250, 250, 
        x + 0,   0,   
    };
        
    glMatrixMode(GL_MODELVIEW);
    glEnableClientState(GL_VERTEX_ARRAY); 
    glVertexPointer(2, GL_SHORT, 0, vertices);                        
    glColor4f(1, 0, 0, 1);
    glDrawArrays(GL_TRIANGLES, 0, 3);   
}

#pragma mark - Touch handling methods

- (void) touchesBegan: (NSSet *) touches withEvent: (UIEvent *) event {	
    CGPoint p = [[touches anyObject] locationInView: self.view];   
    NSLog(@"Touch began at %f, %f", p.x, p.y);
}

- (void) touchesMoved: (NSSet *) touches withEvent: (UIEvent *) event {   
    CGPoint p = [[touches anyObject] locationInView: self.view];  
    NSLog(@"Touch moved at %f, %f", p.x, p.y);
}

#pragma mark - Lifecycle

- (void) viewDidUnload
{
    [super viewDidUnload];
}

- (void) didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
}

// Deprecated since iOS 6.0, but still needed for older versions
- (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) interfaceOrientation
{
    return YES;
}
 
/*
// Available since iOS 6.0
- (BOOL) shouldAutorotate {
    return YES;
}
*/

- (void)dealloc
{
    [eaglContext release];
    [super dealloc];
}

@end
